package com.zhouheng.common.utils.check;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public final class Validators {

    private static final Validator validator =
            Validation.buildDefaultValidatorFactory().getValidator();

    private Validators() {
    }

    public static <T> Map<String, String> validate(T para) {
        Set<ConstraintViolation<T>> violations = validator.validate(para);
        return getErrorMap(violations);
    }

    private static <T> Map<String, String> getErrorMap(Set<ConstraintViolation<T>> set) {
        Map<String, String> errorMap = null;
        if (set != null && set.size() > 0) {
            errorMap = new HashMap<>(set.size());
            String property;
            for (ConstraintViolation<T> cv : set) {
                property = cv.getPropertyPath().toString();
                errorMap.put(property, cv.getMessage());
            }
        }
        return errorMap;
    }

    public static <T> Map<String, String> validate(T obj, Class<?>... groups) {
        Set<ConstraintViolation<T>> set = validator.validate(obj, groups);
        return getErrorMap(set);
    }

    public static <T> Map<String, StringBuffer> validateAll(T obj) {
        Map<String, StringBuffer> errorMap = Collections.emptyMap();
        Set<ConstraintViolation<T>> set = validator.validate(obj);
        if (set != null && set.size() > 0) {
            errorMap = new HashMap<>(set.size());
            String property = null;
            for (ConstraintViolation<T> cv : set) {
                // 这里循环获取错误信息，可以自定义格式
                property = cv.getPropertyPath().toString();
                if (errorMap.get(property) != null) {
                    errorMap.get(property).append("," + cv.getMessage());
                } else {
                    StringBuffer sb = new StringBuffer();
                    sb.append(cv.getMessage());
                    errorMap.put(property, sb);
                }
            }
        }
        return errorMap;
    }

    public static boolean assertValidOk(Object paraObj) {
        Map<String, StringBuffer> stringStringBufferMap = Validators.validateAll(paraObj);
        if (stringStringBufferMap != null && stringStringBufferMap.size() != 0) {
            throw new IllegalArgumentException();
        }
        return true;
    }
}
